package com.tetris.block;

import com.tetris.rule.GameRules;

import java.awt.Color;

/**
 * 方块基类，定义方块的基本属性和行为
 */
public abstract class Block {
    protected int x;           // 方块左上角x坐标
    protected int y;           // 方块左上角y坐标
    protected int[][] shape;   // 方块形状
    protected Color color;     // 方块颜色

    public Block(int x, int y) {
        this.x = x;
        this.y = y;
        // 不在构造函数中调用初始化方法，避免子类字段未初始化
    }

    // 初始化方块形状，由子类实现
    protected abstract void initializeShape();

    // 设置方块颜色，由子类实现
    protected abstract void setColor();

    // 公开的初始化方法，供子类在构造函数中调用
    public void initialize() {
        initializeShape();
        setColor();
    }

    // 获取方块形状
    public int[][] getShape() {
        return shape;
    }

    // 获取旋转后的形状
    public int[][] getRotatedShape(GameRules.Rotation rotation) {
        int rows = shape.length;
        int cols = shape[0].length;
        int[][] rotated = new int[cols][rows];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (rotation == GameRules.Rotation.CLOCKWISE) {
                    rotated[j][rows - 1 - i] = shape[i][j];
                } else {
                    rotated[cols - 1 - j][i] = shape[i][j];
                }
            }
        }

        return rotated;
    }

    // 旋转方块
    public void rotate(GameRules.Rotation rotation) {
        shape = getRotatedShape(rotation);
    }

    // 移动方块
    public void move(GameRules.Direction direction) {
        switch (direction) {
            case LEFT:
                x--;
                break;
            case RIGHT:
                x++;
                break;
            case DOWN:
                y++;
                break;
            default:
                // 不处理向上移动
                break;
        }
    }

    // 设置位置
    public void setPosition(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // 获取x坐标
    public int getX() {
        return x;
    }

    // 获取y坐标
    public int getY() {
        return y;
    }

    // 获取颜色
    public Color getColor() {
        return color;
    }
}
    